package com.hspedu.seckill.controller;

import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.GoodsService;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.vo.GoodsVo;
import com.hspedu.seckill.vo.SeckillEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.spring5.view.reactive.ThymeleafReactiveViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserService userService;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user,HttpServletRequest request,
                         HttpServletResponse response) {

        if(user == null)
            return "login";

        //redis获取页面缓存
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html =(String) valueOperations.get("goodsList");
        if (StringUtils.hasText(html)){
            return html;
        }


        //将user放入model,携带到下一个模板使用
        model.addAttribute("user",user);
        //Vo放入model
        model.addAttribute("goodsList",goodsService.findGoodsVo());

        //没有获取页面信息，手动渲染页面，放入redis
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(),
                request.getLocale(),
                model.asMap());

        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if(StringUtils.hasText(html)){
            //存入redis 60s更新一次
            valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
        }
        return html;
    }

    /**
     * 进入商品详情
     */
    @RequestMapping(value = "/toDetail/{id}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model,User user,@PathVariable Long id,
        HttpServletResponse response,HttpServletRequest request){
        if(user == null)
            return "login";

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html =(String) valueOperations.get("goodsDetail:" + id);
        if (StringUtils.hasText(html)){
            return html;
        }


        model.addAttribute("user",user);

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(id);

        model.addAttribute("goods",goodsVo);


        //秒杀开始时间
        Date startDate = goodsVo.getStartDate();
        //秒杀结束时间
        Date endDate = goodsVo.getEndDate();
        //当前时间
        Date nowDate = new Date();

        //秒杀状态
        int secKillStatus = 0;
        //剩余秒数: >0:还有多久开始秒杀 0:秒杀进行中 -1:秒杀结束
        int remainSeconds = 0;

        if (nowDate.before(startDate)){
            //秒杀未开始
            secKillStatus = SeckillEnum.SECKILL_NOSTART;
            remainSeconds = (int) (startDate.getTime() - nowDate.getTime());
        }else if(nowDate.after(endDate)){
            //秒杀已结束
            secKillStatus = SeckillEnum.SECKILL_OVER;
            remainSeconds = -1;
        }else{
            //秒杀进行中
            secKillStatus = SeckillEnum.SECKILL_START;
            remainSeconds = 0;
        }

        //放入model，给模板页使用
        model.addAttribute("secKillStatus",secKillStatus);
        model.addAttribute("remainSeconds",remainSeconds);

        //没有获取页面信息，手动渲染页面，放入redis
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(),
                request.getLocale(),
                model.asMap());

        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if(StringUtils.hasText(html)){
            //存入redis 60s更新一次
            valueOperations.set("goodsDetail:" + id , html , 60 , TimeUnit.SECONDS);
        }


        return html;
    }
}
